<template>
  <div>
    <!-- 图标面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用戶管理</el-breadcrumb-item>
      <el-breadcrumb-item>用戶列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :md="7" :sm='16' :xs="18">
          <el-input placeholder="请输入内容" v-model="queryInfo.query"
                    clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search"
                       @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :md="4" :sm='8' :xs="6">
            <el-button type="primary"
                       @click="addDialogVisible = true">
                       添加用户
            </el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="phone"></el-table-column>
        <el-table-column label="角色" prop="role"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <!-- scope.row：当前行的值 -->
            <el-switch v-model="scope.row.state" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- scope.row：当前行的值 -->
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row)"></el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeUser(scope.row.id)"></el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" size="mini" icon="el-icon-setting" @click="showSetRoleDialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose">
      <!-- 内容主体 -->
      <el-form ref="addRef" :model="addForm" :rules="addRules" label-width="70px" class="add-form">
          <el-form-item label="用户名" prop="username">
              <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
              <el-input v-model="addForm.password" type="password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
              <el-input v-model="addForm.email" type="email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="phone">
              <el-input v-model="addForm.phone" type="phone"></el-input>
          </el-form-item>
      </el-form>
       <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClose">
      <!-- 内容主体 -->
      <el-form ref="editRef" :model="editForm" :rules="editRules" label-width="70px" class="editform">
          <el-form-item label="用户名" prop="username">
              <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email" type="email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="phone">
              <el-input v-model="editForm.phone" type="phone"></el-input>
          </el-form-item>
      </el-form>
       <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%" @close='setRoleDialogClosed'>
      <!-- 内容主体 -->
      <div>
        <p>当前的用户： {{setRoleForm.username}}</p>
        <p>当前的角色： {{setRoleForm.role}}</p>
        <p>分配新角色：
          <el-select v-model="setRoleForm.newRoleId" placeholder="请选择">
            <el-option v-for="item in rolesList" :key="item.id"
                      :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRoleInfo">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data () {
    // 自定义验证规则 --- 验证普通字符
    var checkWord = (rule, value, callback) => {
      const regWord = /\W/
      if (regWord.test(value)) {
        return callback(new Error('只接受字母、数字和下划线'))
      }

      callback()
    }
    // 自定义验证规则 --- 验证邮箱
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return callback()
      }

      callback(new Error('请输入合法的邮箱'))
    }
    // 自定义验证规则 --- 验证电话
    var checkPhone = (rule, value, callback) => {
      const regPhone = /^[+ \d]{6,}$/
      if (regPhone.test(value)) {
        return callback()
      }

      callback(new Error('请输入合法的手机号'))
    }
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      userList: [],
      total: 0,
      rolesList: [], // 所有角色列表

      addDialogVisible: false, // 是否显示添加用户对话框
      editDialogVisible: false, // 是否显示添加用户对话框
      setRoleDialogVisible: false, // 否显示分配角色对话框
      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        phone: ''
      },
      // 编辑用户的表单数据
      editForm: {},
      // 分配权限的表单数据
      setRoleForm: {},
      // 添加表单的验证规则对象
      addRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' },
          { validator: checkWord, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' },
          { validator: checkWord, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' }
        ]
      },
      // 编辑表单的验证规则对象
      editRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' },
          { validator: checkWord, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' },
          { validator: checkWord, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
        .catch(err => {
          return { data: { status: 500, message: err } }
        })
      console.log(res)
      if (res.status !== 200) return this.$message.error(res.message)
      this.userList = res.data
      this.total = res.meta.total
    },
    handleSizeChange (newSize) {
      // 监听 pagesize 改变的事件
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange (newPage) {
      // 监听 page 改变的事件
      // console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    async userStateChanged (userInfo) {
      // 监听 switch 开关状态的改变
      const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.state}`)
        .catch(err => {
          return { data: { status: 500, message: err } }
        })
      console.log(res)
      if (res.status !== 200) {
        userInfo.state = !userInfo.state
        return this.$message.error('更新用户状态失败')
      }

      this.$message.success('更新用户状态成功')
    },
    addDialogClose () {
      // 监听添加用户对话框的关闭事件
      this.$refs.addRef.resetFields()
    },
    addUser () {
      this.$refs.addRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addForm)
          .catch(err => {
            return { data: { status: 500, message: err } }
          })
        console.log(res)
        if (res.status !== 200) return this.$message.error('添加用户失败')
        this.$message.success('添加用户成功')
        // 隐藏添加用户对话框
        this.addDialogVisible = false
        // 重新获取用户列表数据
        this.getUserList()
      })
    },
    showEditDialog (userInfo) {
      // 打开修改用户对话框
      this.editDialogVisible = true
      this.editForm = userInfo
    },
    editDialogClose () {
      // 监听添加用户对话框的关闭事件
      this.$refs.editRef.resetFields()
    },
    editUser () {
      this.$refs.editRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('users', this.editForm)
          .catch(err => {
            return { data: { status: 500, message: err } }
          })
        console.log(res)
        if (res.status !== 200) return this.$message.error('修改用户信息失败')
        this.$message.success('修改用户信息成功')
        // 隐藏添加用户对话框
        this.editDialogVisible = false
        // 重新获取用户列表数据
        this.getUserList()
      })
    },
    async removeUser (id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .catch(err => err)

      // 这里需要注意
      // 如果用户点击确定，返回值为字符串 confirm
      // 如果用户点击取消，返回值为字符串 cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      const { data: res } = await this.$http.delete('users/' + id)
        .catch(err => {
          return { data: { status: 500, message: err } }
        })
      console.log(res)
      if (res.status !== 200) return this.$message.error('删除失败!')
      this.$message.success('删除成功!')
      this.getUserList()
    },
    async showSetRoleDialog (info) {
      this.setRoleForm = info

      // 展示对话框前获取所有角色的列表
      const { data: res } = await this.$http.get('roles')
        .catch(err => ({ data: { status: 500, message: err } }))
      console.log(res)
      if (res.status !== 200) return this.$message.error('获取角色列表失败!')
      this.$message.success('获取角色列表成功!')
      this.rolesList = res.data

      this.setRoleDialogVisible = true
    },
    async setRoleInfo () {
      // 分配新角色
      if (!this.setRoleForm.newRoleId) {
        return this.$message.error('请选择要分配的角色')
      }

      const { data: res } = await this.$http.put(
        `users/${this.setRoleForm.id}/role`,
        { rid: this.setRoleForm.newRoleId }
      ).catch(err => ({ data: { status: 500, message: err } }))
      console.log(res)
      if (res.status !== 200) return this.$message.error('更新角色失败!')
      this.$message.success('更新角色成功!')
      this.getUserList()
      this.setRoleDialogVisible = false
    },
    setRoleDialogClosed () {
      this.setRoleForm = {}
    }
  }
}
</script>

<style type="less" scoped>
.el-table{
  margin-top: 15px;
  font-size: 12px;
}

.el-pagination{
  margin-top: 15px;
}
</style>
